// packageA/pages/cleanWorkList/cleanWorkList.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        //传参
        paramObj: {},
        //列表
        list: [],
        //页码
        page: 1,
        //是否无更多
        notMore: true,
        //无数据
        showNothing: false,
        //搜索关键词
        searchValue: '',
        //状态筛选 0：未完成，1：完成
        optionState: [{
                text: '所有',
                value: -2
            },
            {
                text: '已取消',
                value: -1
            },
            {
                text: '未完成',
                value: 0
            },
            {
                text: '审批驳回',
                value: 1
            },
            {
                text: '待审批',
                value: 2
            },
            {
                text: '已完成',
                value: 3
            },

        ],
        valueState: -2,
        //接单人筛选
        optionReceive: [{
                text: '所有工单',
                value: 0
            },
            {
                text: '我接单的',
                value: 1
            }
        ],
        valueReceive: 0,
        //登录用户
        user: null,
        //开始时间
        startTime: '开始日期',
        //开始时间选择框
        showStartTime: false,
        //结束时间
        endTime: '结束日期',
        //结束时间选择框
        showEndTime: false,
        //当前时间
        currentStart: new Date().getTime(),
        currentEnd: new Date().getTime(),
        //最小时间
        minDate2: null,
        minDate1: null,
        //最大时间
        maxDate1: new Date().getTime(),
        maxDate2: new Date().getTime(),
        //时间格式
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`
            } else if (type === 'month') {
                return `${value}月`
            } else if (type === 'day') {
                return `${value}日`
            }
            return value
        },
        //查询条件，项目id
        queryProjectIds: [],
        stateStyles:{
            '已取消':'state_cancelled',
            '未完成':'state_incomplete',
            '审批驳回':'state_reject',
            '待审批':'state_approval',
            '已完成':'state_completed',
        },
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let user = app.globalData.userInfo;
        console.log(user);
        if (user) {
            this.setData({
                user: user
            })

            if (user.departObj[0].type == 4) {
                //客户先查询根据地（查完再查工单列表）
                //this.getBaseArea();
                this.getList();
            } else {
                //非客户直接查列表
                this.getList();
            }

        } else {
            wx.redirectTo({
                url: "/pages/login/login?fromCleanWork=" + '1'
            })
        }
    },

    //查询根据地
    getBaseArea() {
        Toast.loading({
            duration: 0,
            forbidClick: true,
            message: '加载中...'
        });

        let user = this.data.user;
        let dObj = user.departObj[0];

        let param = {
            isAuth: false,
            className: 'baseAreaManagement',
            data: {
                searchAll: true,
                selectFields: ['id', 'name', 'departsId', 'projectsId'],
                nbl: Base64.encode(util.timeFormatDay(new Date()))
            }
        }

        //区分什么级别的用户登录（一级部门、大区、项目）
        if (dObj.level == 1) {
            //一级
            param.data.departsId = dObj.id;
        } else if (dObj.isProject) {
            //项目
            param.data.projectsId = dObj.id;
        } else if (dObj.isRegion) {
            //大区
            param.data.departsId = dObj.companyId;
        } else {
            //无数据
            this.notDatas();
            //都不是的不能查询
            return;
        }

        CommonService.goFindList(param).then(res => {
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                let result = res.data.data.result;
                console.log('根据地');
                console.log(result);

                //取出项目id
                let proIds = [];
                result.forEach(item => {
                    proIds = proIds.concat(item.projectsId);
                });

                //再把数据权限加进去
                proIds = proIds.concat(user.dataAuthorityOfUser.depart);

                //去重
                proIds = util.arrayRepeatEmpty(proIds);

                console.log('所有项目');
                console.log(proIds);

                if (proIds.length) {
                    this.setData({
                        queryProjectIds: proIds
                    })

                    //获取工单列表
                    this.getList();
                }

            } else {
                //无数据
                this.notDatas();
            }
        }).catch((error) => {
            //无数据
            this.notDatas();
        })
    },




    //获取列表数据
    getList() {
        let dataObj = {
            selectFields: ['id', 'taskName', 'inspectionTaskId', 'project', 'taskType', 'taskDescribe', 'taskRequire', 'imgCountRequire', 'taskRange', 'createdUser', 'inspectionDate', 'state', 'img', 'completeDate', 'mediaList', 'dataAuthority', 'taskApprover', 'currentApprover', 'approveRecord', 'handler'],
            sort: {
                inspectionDate: -1,
                state:-1
            },
            page: {
                page: this.data.page,
                pageSize: 10
            }
        }


        //筛选状态
        if (this.data.valueState != -2) {
            dataObj.state = this.data.valueState;
        }

        //接单人
        if (this.data.valueReceive == 1) {
            dataObj['handler.id'] = this.data.user.id;
        }

        //模糊查询
        if (this.data.searchValue) {
            dataObj['project.name'] = '%' + this.data.searchValue + '%';
        }

        //创建时间
        if (this.data.startTime != '开始日期' && this.data.endTime != '结束日期') {
            dataObj.complex = [{
                and: {
                    inspectionDate: {
                        ">=": this.data.startTime + " 00:00:00",
                        "<=": this.data.endTime + " 23:59:59"
                    }
                }
            }]
        } else {
            
            let nowDay = util.timeFormatDay(new Date())
            dataObj.inspectionDate = {
                "<=": nowDay + " 23:59:59"
            }
        }

        let param = {
            className: 'inspectionTaskList',
            data: dataObj
        }
        console.log("param")
        console.log(param)
        CommonService.goFindList(param).then(res => {
            console.log(2);
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                let result = res.data.data.result;

                result.forEach(item => {
                    //状态
                    switch (item.state) {
                        case -1:
                            item.self_state = '已取消';
                            item.self_stateClass = 'c-5';
                            break;
                        case 0:
                            item.self_state = '未完成';
                            item.self_stateClass = 'c-4';
                            break;
                        case 1:
                            item.self_state = '审批驳回';
                            item.self_stateClass = '.c-1';
                            break;
                        case 2:
                            item.self_state = '待审批';
                            item.self_stateClass = 'c-3';
                            break;
                        case 3:
                            item.self_state = '已完成';
                            item.self_stateClass = 'c-2';
                            break;
                    }
                    //巡检时间
                    if (item.inspectionDate) {
                        item.inspectionDate = item.inspectionDate.substring(0, 10);
                    }
                    //创建时间
                    if (item.submissionTime) {
                        item.self_submissionTime = util.timeFormat(item.submissionTime);
                    }

                    //完成时间
                    if (item.completionTime) {
                        item.self_completionTime = util.timeFormat(item.completionTime);
                    }
                });

                console.log('任务清单列表');
                console.log(result);

                this.setData({
                    list: this.data.list.concat(result)
                })
                Toast.clear();
            } else {
                this.setData({
                    notMore: false
                })
                if (this.data.page == 1) {
                    this.setData({
                        showNothing: true
                    })
                    Toast.clear();
                } else {
                    Toast.fail('没有更多了');
                }
            }
        }).catch((error) => {
            this.setData({
                showNothing: true
            })
            Toast.clear();
        })
    },

    //无数据
    notDatas() {
        this.setData({
            showNothing: true
        })
        Toast.clear();
    },

    //刷新列表和页码
    refreshListAndPage() {
        this.setData({
            list: [],
            page: 1,
            notMore: true,
            showNothing: false
        })
        this.getList();
    },

    //获取搜索词
    onChangeSearch(e) {
        this.setData({
            searchValue: e.detail.value.trim(),
        })
    },

    //点击搜索
    onSearch() {
        this.refreshListAndPage();
    },

    //跳转添加
    goToAdd() {
        wx.navigateTo({
            url: "/packageA/pages/cleanWorkAdd/cleanWorkAdd"
        })
    },

    //跳转编辑
    goToEdit(e) {
        let detail = e.currentTarget.dataset.detail;
        let obj = {
            id: detail.id
        }
        wx.navigateTo({
            url: "/packageA/pages/cleanWorkAdd/cleanWorkAdd?paramObj=" + JSON.stringify(obj)
        })
    },

    //跳转详情
    goToLook(e) {
        let detail = e.currentTarget.dataset.detail;
        let paramObj = {
            id: detail.id,
            type: "detail"
        }
        console.log(detail);
        wx.navigateTo({
            url: "/packageB/pages/taskListsubmit/taskListsubmit?paramObj=" + JSON.stringify(paramObj)
        })
    },

    //跳转处理
    goToApprove(e) {
        let detail = e.currentTarget.dataset.detail;
        let paramObj = {
            id: detail.id,
            type: "approve"
        }
        console.log(detail);
        wx.navigateTo({
            url: "/packageB/pages/taskListsubmit/taskListsubmit?paramObj=" + JSON.stringify(paramObj)
        })
    },

    //跳转物业工单
    goTokeepOrder(e) {
        let detail = e.currentTarget.dataset.detail;
        let paramObj = {
            taskListId: detail.id,
            type: "fromTask"
        }
        wx.navigateTo({
            url: "/packageA/pages/cleanWorkAdd/cleanWorkAdd?paramObj=" + JSON.stringify(paramObj)
        })
    },

    //删除
    onDelete(e) {
        Dialog.confirm({
            title: '确定删除此工单吗',
            confirmButtonText: '确定',
            cancelButtonText: '不删除了'
        }).then(() => {
            let detail = e.currentTarget.dataset.detail;

            let param = {
                className: "cleanKeepingOrder",
                data: {
                    id: detail.id
                }
            }

            CommonService.goDelete(param).then(res => {
                if (res.statusCode == 200 && res.data.success == true) {
                    Toast.success('已删除');
                    //刷新列表和页码
                    this.refreshListAndPage();
                } else {
                    Toast.fail('操作失败');
                }
            }).catch((error) => {
                Toast.fail('操作失败');
            })

        }).catch(() => {});
    },

    //预览图片
    onPreviewImage(e) {
        let detail = e.target.dataset.detail;
        let src = e.target.dataset.src;

        let newArr = [];
        for (let i = 0; i < detail.length; i++) {
            newArr.push(detail[i].url);
        }

        wx.previewImage({
            current: src,
            urls: newArr
        })
    },

    //选择状态
    onChangeState({
        detail
    }) {
        this.setData({
            valueState: detail
        })
        console.log("detail");
        console.log(detail);
        this.refreshListAndPage();
    },

    //选择我接单的/所有
    onChangeReceive({
        detail
    }) {
        this.setData({
            valueReceive: detail
        })
        this.refreshListAndPage();
    },

    //接单
    onStart(e) {
        Dialog.confirm({
            title: '确定提交吗',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }).then(() => {

            let detail = e.currentTarget.dataset.detail;
            let paramObj = {
                id: detail.id,
                type: "submit"
            }
            console.log(detail);
            wx.navigateTo({
                url: "/packageB/pages/taskListsubmit/taskListsubmit?paramObj=" + JSON.stringify(paramObj)
            })
        }).catch(() => {});
    },

    //完成
    onComplete(e) {
        Dialog.confirm({
            title: '确定完成此工单吗',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }).then(() => {
            let detail = e.currentTarget.dataset.detail;

            let param = {
                className: "cleanKeepingOrder",
                data: {
                    id: detail.id,
                    //状态 1已完成,2未受理,3受理中
                    state: 1,
                    //完成时间
                    completionTime: util.timeFormat(new Date())
                }
            }

            CommonService.goSave(param).then(res => {
                if (res.statusCode == 200 && res.data.success == true) {
                    Toast.success('已接单');
                    //刷新列表和页码
                    this.refreshListAndPage();
                } else {
                    Toast.fail('操作失败');
                }
            }).catch((error) => {
                Toast.fail('操作失败');
            })

        }).catch(() => {});
    },

    //显示开始时间
    onShowStartTime() {
      const nowTime = new Date().getTime();
      // 计算30天的毫秒数（30天 × 24小时 × 60分钟 × 60秒 × 1000毫秒）
      const thirtyDaysMs = 30 * 24 * 60 * 60 * 1000;
      const thirtyDaysAgoTime = nowTime - thirtyDaysMs;
      const thiryDaysAfterTime = nowTime + thirtyDaysMs
      console.log(new Date(thirtyDaysAgoTime));
        this.setData({
            showStartTime: true,
            minDate1:new Date(thirtyDaysAgoTime).getTime(),
        })
    },

    //隐藏开始时间
    onCloseStartTime() {
        this.setData({
            showStartTime: false
        })
    },

    //确认开始时间
    onConfirmStartTime(e) {
        this.setData({
            currentStart: e.detail,
            minDate2: e.detail,
            startTime: util.timeFormatDay(e.detail),
        })
        this.onCloseStartTime();

        if (this.data.endTime != '结束日期') {
            this.refreshListAndPage();
        }
    },

    //显示结束时间
    onShowEndTime() {
      const nowTime = new Date().getTime();
      // 计算30天的毫秒数（30天 × 24小时 × 60分钟 × 60秒 × 1000毫秒）
      const thirtyDaysMs = 30 * 24 * 60 * 60 * 1000;
      const thiryDaysAfterTime = nowTime + thirtyDaysMs
        this.setData({
            showEndTime: true,
            minDate2:new Date(thiryDaysAfterTime).getTime(),
        })
    },

    //隐藏结束时间
    onCloseEndTime() {
        this.setData({
            showEndTime: false
        })
    },

    //确认结束时间
    onConfirmEndTime(e) {
        this.setData({
            currentEnd: e.detail,
            maxDate1: e.detail,
            endTime: util.timeFormatDay(e.detail),
        })
        this.onCloseEndTime();

        if (this.data.startTime != '开始日期') {
            this.refreshListAndPage();
        }
    },

    //清除时间
    onCancelTime() {
        this.setData({
            startTime: '开始日期',
            endTime: '结束日期'
        })

        this.onCloseStartTime();
        this.onCloseEndTime();
        this.refreshListAndPage();
    },

    //跳转验收评价
    goToCheck({
        currentTarget
    }) {
        let detail = currentTarget.dataset.detail;
        let obj = {
            id: detail.id
        }
        wx.navigateTo({
            url: "/packageA/pages/cleanWorkCheck/cleanWorkCheck?paramObj=" + JSON.stringify(obj)
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        if (this.data.notMore) {
            this.setData({
                page: this.data.page + 1
            })
            this.getList();
        }
    },

})